import { defineStore } from 'pinia'


function getNewDiscountRate (rate: number): Promise<number> {
  return new Promise ((resolve, reject) => {
    setTimeout(() => {
      rate = Math.random()
      console.log('New discount rate:', rate)
       resolve(rate)
      // reject(rate)
    }, 1000)
  })
}

export default defineStore('cart', {

  

  state() {
    const discountRate = 1
    return {
      name: '购物车',
      books: [
        {
          name: 'ES6',
          price: 50,
          count:0
        },
        {
          name: '微服务架构设计模式',
          price: 139,
          count:0
        },
        {
          name: '数据密集型应用系统设计',
          price: 128,
          count:0
        }
      ],
      discountRate
    }
  },
  getters: {
    price (): number {
      return this.books.reduce((init: number, curValue: BookItem) => {
        return init += curValue.price * curValue.count
      }, 0)
    },
    
    /*price: (state) => {
      return state.books.reduce((init: number, curValue: BookItem) => {
        return init += curValue.price * curValue.count
      }, 0)
    }*/
  },
  actions: {
    async changeDiscountRate () {
      this.discountRate = await getNewDiscountRate(this.discountRate)
    }
  },
})

export type BookItem = {
  name:string,
  price: number,
  count: number
}

